package com.songcha.sakura.mvvm.home.cate

import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.songcha.library_base.interfaces.ILoadMoreData
import com.songcha.sakura.R
import com.songcha.sakura.bean.ComicListBean
import com.songcha.sakura.databinding.FragmentHomeCategoryBinding
import com.songcha.sakura.event.HomeComicGetCompletedEvent
import com.songcha.sakura.ui.adapter.ComicAdapter
import com.songcha.sakura.databinding.ItemComicBinding
import com.songcha.sakura.ui.decoration.HomeComicItemDecoration
import com.songcha.sakura.util.*
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.songcha.sakura.ui.base.BaseComicRefreshLoadMoreMvvmFragment
import org.greenrobot.eventbus.EventBus

class HomeCateFragment : BaseComicRefreshLoadMoreMvvmFragment<HomeCateViewModel, FragmentHomeCategoryBinding>(),
    ILoadMoreData {
    companion object{
        val TAG:String= HomeCateFragment::class.java.simpleName
    }

    private var mAdapter:ComicAdapter<ItemComicBinding>?=null
    private var mIndex=0

    //constructor():this(0)

    override fun getLayoutId(): Int {
        return R.layout.fragment_home_category
    }

    override fun initView(savedInstanceState: Bundle?){
        super.initView(savedInstanceState)

        arguments?.let {
            mIndex=it.getInt("index",0)
        }

        /*databinding.srlHomeCate.setOnRefreshListener{
            viewModel.onRefreshing()
            viewModel.getData(mIndex)
        }

        databinding.srlHomeCate.setOnLoadMoreListener{
            viewModel.onLoadingMore()
            viewModel.getComicList(mIndex)
        }*/

        onLoading()
       // viewModel.getData(mIndex)

       /* viewModel.comicList.observe(viewLifecycleOwner){
            if(it!=null && !viewModel.isLoadingMore){
                initData(it)
            }
        }*/

        val mCheckForGapMethod=StaggeredGridLayoutManager::class.java.getDeclaredMethod("checkForGaps")
        mCheckForGapMethod.isAccessible=true
        val mMarkItemDecorInsetsDirtyMethod=RecyclerView::class.java.getDeclaredMethod("markItemDecorInsetsDirty")
        mMarkItemDecorInsetsDirtyMethod.isAccessible=true

        databinding.rcvHomeCate.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val result=mCheckForGapMethod.invoke(recyclerView.layoutManager) as Boolean
                if(result){
                    mMarkItemDecorInsetsDirtyMethod.invoke(recyclerView)
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val layoutManager = recyclerView.getLayoutManager()
                if (layoutManager is StaggeredGridLayoutManager) {
                    //防止第一行顶部有空白区域
                    //(layoutManager).invalidateSpanAssignments()
                }

            }
        })

    }

    override fun onGetData() {
        viewModel.getData(mIndex)
    }

    override fun onGetLoadMoreData() {
        viewModel.getData(mIndex)
    }


    override fun isNeedShowLoad(): Boolean {
        return true
    }

    override fun onRetry() {
        super.onRetry()
        viewModel.getData(mIndex)
    }


    private fun initData(bean: ComicListBean){

    }



    private fun setComicAdapterListener(adapter: ComicAdapter<ItemComicBinding>){
        adapter.setOnItemChildClickListener{ad,view,position->
            val comic=ad.data[position] as ComicListBean.ComicBean
            MyJumpUtil.toComicDetail(requireContext(),comic)
        }

    }




    override fun onDestroyView() {
        super.onDestroyView()
    }


    override fun onLoadMoreError(e: Throwable) {
        super.onLoadMoreError(e)

    }
    override fun onLoading() {
        super.onLoading()
    }


    override fun onLoadError(e: Throwable) {
        super.onLoadError(e)
        //LogUtil.log("aaa onLoadError",e.message)
    }


    override fun getRefreshLayout(): SmartRefreshLayout {
       return databinding.srlHomeCate
    }

    override fun getListAdapter(): RecyclerView.Adapter<BaseViewHolder>? {
        return mAdapter as RecyclerView.Adapter<BaseViewHolder>?
    }

    override fun initListData() {
        databinding.rcvHomeCate.apply {
            val staggeredGridLayoutManager=StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
            //防止交换item
            //staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE)
            layoutManager=staggeredGridLayoutManager

            if(itemDecorationCount==0)
                addItemDecoration(HomeComicItemDecoration())

            mAdapter=ComicAdapter(context, R.layout.item_comic, viewModel.rlst.value!!)
            adapter = mAdapter

            setComicAdapterListener(mAdapter!!)

            //惯性滚动时停止加载图片，防止卡顿
            addOnScrollListener(object : RecyclerView.OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    when(newState){
                        RecyclerView.SCROLL_STATE_IDLE,RecyclerView.SCROLL_STATE_DRAGGING->{
                            Glide.with(context).resumeRequests()
                        }
                        RecyclerView.SCROLL_STATE_SETTLING->{
                            Glide.with(context).pauseRequests()
                        }
                    }
                }
            })
        }

        databinding.srlHomeCate.finishRefresh()

        //saveHomeCache(bean)
        val clb=ComicListBean()
        clb.data=viewModel.rlst.value!!
        EventBus.getDefault().post(HomeComicGetCompletedEvent(mIndex,clb))
    }


}